<template>
  <div class="departmentDrug-add-page">
    <!-- 头部搜索 -->
    <header>
      <!-- 修改版 -->
      <div style="display: flex">
        <Button
          v-if="mode === 'add' && hospitalInfo.hospitalType != 1"
          type="primary"
          @click="chooseDep"
          class="buttonbox"
          >
		  	<i class = "iconfont icon-add" style="font-size:14px;margin-right:5px"></i>选择医疗机构
		</Button
        >
        <div class="fun-part" v-if="mode !== 'review'">
			<i-button
				@click="handleShowUploadModal"
				:disabled="!finalRecord.id"
				type="primary"
				>
				<i class = "iconfont icon-add" style="font-size:14px;margin-right:5px"></i>选择药品目录
			</i-button
          >
          <a @click="download" style="margin-left: 15px" href="javascript:;"
            >下载药品信息导入模版</a
          >
        </div>
      </div>
      <div
        v-if="finalRecord.id"
        style="display: flex; justify-content: space-between"
      >
        <div class="filter-part">
          <template v-if="finalRecord.id">
            <div class="filter-item">
              <label>医疗机构ID：</label>
              <div class="content">{{ finalRecord.id }}</div>
            </div>
            <div class="filter-item">
              <label>医疗机构名称：</label>
              <div class="content">{{ finalRecord.hospitalName }}</div>
            </div>
            <div class="filter-item">
              <label>联系电话：</label>
              <div class="content">{{ finalRecord.linkmanTelephone }}</div>
            </div>
            <div class="filter-item">
              <label>地址：</label>
              <div class="content">{{ finalRecord.hosAddr }}</div>
            </div>
          </template>
        </div>
      </div>
    </header>
    <!-- 列表 -->
    <Tabs value="success" v-model="currentTab">
      <TabPane :label="labelSuccess" name="success">
        <Table
          border
          size="small"
          :columns="columnsSuccess"
          :data="successList"
          :loading="successTableloading"
          no-data-text="未查询到符合条件的记录"
          stripe
        ></Table>
        <div class="page">
          <Page :total="pageSuccess.count" :current="pageSuccess.pageNo"
                :page-size="pageSuccess.pageSize" show-total show-elevator @on-change="successPageChange"/>
        </div>
        <div class="btn-group">
          	<Button class="btn-cancel btn" type="ghost" @click="handleCancel"
            >
				<i class = "iconfont icon-butongyi" style="font-size:14px;margin-right:5px"></i>取消
			</Button
          >
        </div>
      </TabPane>
      <TabPane
        v-if="this.mode !== 'review'"
        :label="labelPending"
        name="pending"
      >
        <Table
          border
          size="small"
          :columns="columnsPending"
          :data="pendingList"
          no-data-text="未查询到符合条件的记录"
          stripe
        ></Table>
        <div class="btn-group">
          <Button
            class="btn-save"
            type="primary"
            :disabled="!pendingList.length"
            :loading="saveBtnLoading"
            v-if="mode !== 'review' && currentTab === 'pending'"
            @click="handleSave"
            >保存对照结果</Button
          >
          	<Button class="btn-cancel btn" type="ghost" @click="handleCancel"
            >
				<i class = "iconfont icon-butongyi" style="font-size:14px;margin-right:5px"></i>取消
			</Button
          >
        </div>
      </TabPane>
      <TabPane :label="labelFail" name="fail">
        <Table
          border
          size="small"
          :columns="columnsFailure"
          :data="failList"
          :loading="failureTableloading"
          no-data-text="未查询到符合条件的记录"
          stripe
        ></Table>
        <div class="page">
          <Page :total="pageFailure.count" :current="pageFailure.pageNo"
                :page-size="pageFailure.pageSize" show-total show-elevator @on-change="failurePageChange"/>
        </div>
        <div class="btn-group">
          	<Button class="btn-cancel btn" type="ghost" @click="handleCancel"
            >
				<i class = "iconfont icon-butongyi" style="font-size:14px;margin-right:5px"></i>取消
			</Button>
        </div>
      </TabPane>
      <TabPane
        v-if="this.mode !== 'review'"
        :label="labelHospital"
        name="hospitalPage"
      >
        <div style="width: 100%; height: 50px">
          <div
            v-if="finalRecord.id"
            style="float: right; margin: 10px 0; display: flex"
          >
            <div
              style="margin-right: 10px"
              v-if="
                hospitaldata.length > 0 &&
                hospitaldata[0].compareResult == '未对照'
              "
            >
              <Button
                v-if="mode === 'add' && hospitalInfo.hospitalType != 1"
                type="primary"
                :disabled="disabledContrast"
                @click="contrast(finalRecord.id)"
                class="buttonbox"
                >对照</Button
              >
            </div>
            <div style="margin-right: 10px">
              <Button
                v-if="mode === 'add' && hospitalInfo.hospitalType != 1"
                type="primary"
                @click="lookdirectoryPage(1)"
                :disabled="lookDisabled"
                class="buttonbox"
                >查看院内数据</Button
              >
            </div>
            <div>
              <Button
                type="primary"
                :disabled="disabled"
                @click="directory"
                class="buttonbox"
                >同步院内目录</Button
              >
            </div>
          </div>
          <div class="clear"></div>
        </div>
        <Table
          border
          size="small"
          :columns="hospitalColumns"
          :data="hospitaldata"
          no-data-text="未查询到符合条件的记录"
          stripe
          style="width: 100%"
        ></Table>
        <div class="page">
          <Page :total="pageHospital.count" :current="pageHospital.pageNo"
                :page-size="pageHospital.pageSize" show-total show-elevator @on-change="lookdirectoryPage"/>
        </div>
        <div class="btn-group">
          <Button
            class="btn-save"
            type="primary"
            :disabled="!hospitaldata.length || saveDisabled"
            :loading="saveBtnLoading"
            @click="handledrugSave"
            >保存对照结果</Button
          >
          <Button
            class="btn-save"
            type="primary"
            :disabled="!hospitaldata.length || delDisabled"
            :loading="saveBtnLoading"
            @click="handledrugDel"
            >删除对照记录</Button
          >
          	<Button class="btn-cancel btn" type="ghost" @click="handleCancel"
            >
				<i class = "iconfont icon-butongyi" style="font-size:14px;margin-right:5px"></i>取消
			</Button
          >
        </div>
      </TabPane>
    </Tabs>
    <!-- 选择医疗机构弹窗 -->
    <departmentChoose v-model="showChooseDrugModal" :onOk="handleModalSave" />
    <!-- 选择药品目录上传弹窗 -->
    <Modal
      :mask-closable="false"
      v-model="showUploadModal"
      title="上传药品目录弹窗"
      class="drugmanagement-departmentdrug-add-uplpadModal"
    >
      <div class="download" @click="download">
        <a href="javascript:;">下载药品信息导入模版</a>
      </div>
      <div class="uploading">
        <Upload
          ref="upload"
          multiple
          type="drag"
          :data="{
            json: JSON.stringify({ hospitalId: finalRecord && finalRecord.id }),
          }"
          :action="uploadUrl"
          :on-success="handleSuccess"
          :headers="fromData"
          :before-upload="
            () => {
              uploading = true;
              $refs['upload'].clearFiles();
            }
          "
        >
          <div style="padding: 20px 0">
            <Icon
              type="ios-cloud-upload"
              size="52"
            ></Icon>
            <p>上传填写好的药品信息导入表</p>
          </div>
        </Upload>
      </div>
      <Spin size="large" type="load-c" fix v-if="uploading"></Spin>
    </Modal>
    <!-- 忽略差异选择弹窗 -->
    <Modal
      v-model="showChooseDrugModal2"
      title="忽略差异选择弹窗"
      width="1100px"
      class="drugmanagement-departmentdrug-add-choose"
    >
      <div class="Institutionalregistration">
        <div class="container">
          <div class="list">
            <Table
              border
              :columns="modalColumn2"
              :data="modalData2"
              stripe
              :row-class-name="rowClassName"
              :loading="modalTableLoading2"
              @on-row-click="onRowClick2"
              no-filtered-data-text="未查询到符合条件的记录"
            ></Table>
          </div>
          <div class="page">
            <Page :total="modalCount2" :current="modalFilterObj2.pageNo" :page-size="modalFilterObj2.pageSize" show-total show-elevator @on-change="modalPageChange2"/>
          </div>	
        </div>
      </div>
      <div class="btn-group">
        <Button
          class="save"
          type="primary"
          :disabled="currentChoose2.id !== 0 && !currentChoose2.id"
          :loading="saveLoading2"
          @click="handleModalSave2"
          >确认选择</Button
        >
      </div>
    </Modal>

    <medicalModal v-model="showMedicalModal" :drugId="curDrug.standardId" />
  </div>
</template>

<script>
import api from "@/api/commonApi";
import newfourLevelLinkage from "@/components/newfourLevelLinkage";
import departmentChoose from "@/components/choose/departmentChoose";
import medicalModal from "./medicalModal";
import { Tabs, TabPane, Page, DatePicker } from "view-design";
const columns = [
  { type: "sum", title: "排序", width: 80, align: "center", fixed: "left",
    render: (h, params) => {
        let sum = (filterObj.pageNo-1)*filterObj.pageSize + params.index +1;
        return h("span", sum);
    }
  },
  { title: "医疗机构药品ID", minWidth: 100, key: "hisId", align: "center" },
  { title: "医疗机构药品通用名", minWidth: 100, key: "ypmc", align: "center" },
  {
    title: "标准库药品通用名",
    minWidth: 100,
    key: "standardYpmc",
    align: "center",
  },
  { title: "医疗机构剂型", minWidth: 100, key: "ypjx", align: "center" },
  { title: "标准库剂型", minWidth: 100, key: "standardYpjx", align: "center" },
  { title: "医疗机构规格", minWidth: 100, key: "ypgg", align: "center" },
  { title: "标准库规格", minWidth: 100, key: "standardYpgg", align: "center" },
  { title: "医疗机构厂家", minWidth: 100, key: "scqymc", align: "center" },
  {
    title: "标准库厂家",
    minWidth: 100,
    key: "standardScqymc",
    align: "center",
  },
  {
    title: "医疗机构药品编码",
    minWidth: 100,
    key: "hisCode",
    align: "center",
  },
  {
    title: "标准库药品编码",
    minWidth: 100,
    key: "standardCode",
    align: "center",
  },
  { title: "医疗机构批准文号", minWidth: 100, key: "pzwh", align: "center" },
  {
    title: "标准库批准文号",
    minWidth: 100,
    key: "standardPzwhd",
    align: "center",
  },
  {
    title: "对照结果",
    minWidth: 100,
    key: "compareResult",
    align: "center",
    fixed: "right",
    render(h, params) {
      const color = params.row.type ? "red" : "green";
      return <span style={`color: ${color}`}>{params.row.compareResult}</span>;
    },
  },
];
const filterObj = {
  pageNo: 1,
  pageSize: "10",
};
const modalFilterObj2 = {
  pageNo: 1,
  pageSize: 10,
};
export default {
  components: {
    newfourLevelLinkage,
    departmentChoose,
    medicalModal,
    Tabs,
    TabPane,
  },
  props: {
    mode: String,
    hospitalInfo: Object,
  },
  data() {
    const that = this;
    return {
      currentTab: "success",
      successTableLoading: false,
      failureTableLoading: false,
      uploadUrl: "/api"+api.insertBatchDrug2,
      uploading: false,
      count: 0,
      pageNo: 1,
      pageSize: 10,
      modalCount: 0,
      loading: false,
      modalTableLoading: false,
      saveBtnLoading: false,
      finalRecord: {
        id: this.$route.query.hospitalId && this.$route.query.hospitalId,
        hospitalName: this.$route.query.hospitalName,
        linkmanTelephone: this.$route.query.linkmanTelephone,
        hosAddr: this.$route.query.hosAddr,
      },
      columnsSuccess: [
        ...columns,
        {
          title: "设置",
          key: "_operate",
          width: 100,
          fixed: "right",
          render: (h, params) => {
            return h(
              "a",
              {
                props: {},
                on: {
                  click() {
                    that.showMedicalModal = true;
                    that.curDrug = params.row;
                  },
                },
              },
              "所在药店"
            );
          },
        },
      ],
      pageSuccess: {
        pageNo: 1,
        pageSize: 10,
        count: 0,
      },
      columnsPending: [
        ...columns,
        {
          title: "处理",
          key: "operate",
          width: 100,
          align: "center",
          fixed: "right",
          render: (h, params) => {
            let self = this;
            // const curItem = this.pendingList.filter(
            //   (item) => params.row.id === item.id
            // )[0];
            return h("div", [
              h(
                "Checkbox",
                {
                  props: {
                    value: params.row.del
                  },
                  on: {
                    // "on-change": e => {
                    // 	curItem.del = e;
                    // }
                    "on-change": () => {
                        this.del(params.row)
                      }
                    
                  }
                },
                "删除"
              ),
            ]);
          },
        },
      ],
      columnsFailure: [
        ...columns,
        {
          title: "人工处理结果",
          key: "operate",
          align: "left",
          width: 200,
          fixed: "right",
          render: (h, params) => {
            let self = this;
            return this.genRadioByType(h, params);
          },
        },
        {
          title: "处理状态",
          width: 100,
          key: "handlingType",
          fixed: "right",
          render(h, params) {
            return params.row.manualHandling ? (
              <span style="color: green">已处理</span>
            ) : (
              <span>待处理</span>
            );
          },
        },
      ],
      pageFailure: {
        pageNo: 1,
        pageSize: 10,
        count: 0,
      },
      // 人工处理弹窗相关
      curRecord: {}, // 当前选中的失败项。
      showChooseDrugModal2: false,
      showdirectory: false,
      modalColumn2: [
        {
          title: " ",
          key: "dataOrigin",
          align: "center",
        },
        { title: "医疗机构药品通用名", key: "ypmc", align: "center" },
        { title: "医疗机构剂型", key: "ypjx", align: "center" },
        { title: "医疗机构规格", key: "ypgg", align: "center" },
        { title: "医疗机构厂家", key: "scqymc", align: "center" },
        { title: "医疗机构药品编码", key: "hisCode", align: "center" },
        { title: "医疗机构批准文号", key: "pzwh", align: "center" },
        {
          title: "选择",
          key: "id",
          width: 70,
          align: "center",
          render: (h, params) => {
            let flag = false;
            if (this.currentChoose2.id === params.row.id) {
              flag = true;
            } else {
              flag = false;
            }
            let self = this;
            return (
              params.row.canCheck &&
              h("div", [
                h("Radio", {
                  props: {
                    value: flag,
                  },
                  on: {
                    "on-change": () => {
                      self.currentChoose2 = params.row;
                    },
                  },
                }),
              ])
            );
          },
        },
      ],
      currentChoose2: {}, // 忽略差异或替换原匹配结果弹窗内选中的项。
      modalData2: [],
      modalFilterObj2: this.deepClone(modalFilterObj2),
      modalCount2: null,
      modalTableLoading2: false,
      // data: [],
      successList: [],
      pendingList: [],
      failList: [],
      modalData: [],
      showChooseDrugModal: false,
      modalPageList: [
        {
          value: 10,
          label: 10,
        },
        {
          value: 20,
          label: 20,
        },
        {
          value: 50,
          label: 50,
        },
      ],
      showUploadModal: false,
      labelSuccess: (h) => {
        return h("div", [
          h("span", "对照成功已入库列表"),
          h("Badge", {
            props: {
              count: this.pageSuccess.count,
            },
          }),
        ]);
      },
      labelPending: (h) => {
        return h("div", [
          h("span", "新导入可入库列表"),
          h("Badge", {
            props: {
              count: this.pendingList.length && this.pendingList.length,
            },
          }),
        ]);
      },
      labelFail: (h) => {
        return h("div", [
          h("span", "异常数据列表"),
          h("Badge", {
            props: {
              count: this.pageFailure.count,
            },
          }),
        ]);
      },
      labelHospital: (h) => {
        return h("div", [
          h("span", "院内数据列表"),
          h("Badge", {
            props: {
              count: this.pageHospital.count,
            },
          }),
        ]);
      },
      rowClassName(row, index) {
        if (index === 2) {
    
        }
        return "";
      },
      showMedicalModal: false,
      curDrug: {},
      disabled: false,
      hospitalColumns: [
        {
          type: "index",
          title: "排序",
          width: 80,
          align: "center",
          fixed: "left",
        },
        {
          title: "医疗机构药品ID",
          minWidth: 100,
          key: "hisdmGd",
          align: "center",
          render: (h, params) => {
            let hisdmGd = params.row.hisId;
            return hisdmGd;
          },
        },
        {
          title: "医疗机构药品通用名",
          minWidth: 100,
          key: "itemName",
          align: "center",
        },
        {
          title: "标准库药品通用名",
          minWidth: 100,
          key: "standardYpmc",
          align: "center",
        },
        {
          title: "医疗机构剂型",
          minWidth: 100,
          key: "dose",
          align: "center",
          // render: (h, params) => {
          //   let ypjx = params.row.jx;
          //   return ypjx;
          // },
        },
        {
          title: "标准库剂型",
          minWidth: 100,
          key: "standardYpjx",
          align: "center",
        },
        {
          title: "医疗机构规格",
          minWidth: 100,
          key: "ypgg",
          align: "center",
          render: (h, params) => {
            let ypgg = params.row.itemSpec;
            return ypgg;
          },
        },
        {
          title: "标准库规格",
          minWidth: 100,
          key: "standardYpgg",
          align: "center",
        },
        {
          title: "医疗机构厂家",
          minWidth: 100,
          key: "vendor",
          align: "center",
          // render: (h, params) => {
          //   let scqymc = params.row.sccj;
          //   return scqymc;
          // },
        },
        {
          title: "标准库厂家",
          minWidth: 100,
          key: "standardScqymc",
          align: "center",
        },
        {
          title: "医疗机构药品编码",
          minWidth: 100,
          key: "itemCode",
          align: "center",
        },
        {
          title: "标准库药品编码",
          minWidth: 100,
          key: "standardCode",
          align: "center",
        },
        {
          title: "医疗机构批准文号",
          minWidth: 100,
          key: "pzwh",
          align: "center",
          // render: (h, params) => {
          //   let scqymc = params.row.sccj;
          //   return scqymc;
          // },
        },
        {
          title: "标准库批准文号",
          minWidth: 100,
          key: "standardPzwhd",
          align: "center",
        },
        {
          title: "对照结果",
          minWidth: 100,
          key: "compareResult",
          align: "center",
          fixed: "right",
          render(h, params) {
            const color = params.row.type ? "red" : "green";
            return (
              <span style={`color: ${color}`}>{params.row.compareResult}</span>
            );
          },
        },
        {
          title: "处理",
          key: "operate",
          width: 100,
          align: "center",
          fixed: "right",
          render: (h, params) => {
            let id = params.row.hospitalid;
            let remove = null;
            // let self = this;
            const removeItem = this.hospitaldata.filter(
              (item) => params.row.id === item.id
            )[0];
            remove = h(
              "Checkbox",
              {
                props: {
                  value: removeItem.del,
                },
                on: {
                  "on-change": (e) => {
                    console.log(e);
                    removeItem.del = e;
                    this.removeId = [];
                    this.hospitaldata.forEach((item) => {
                      if (item.del) {
                        delete !item.del;
                        this.removeId.push(item.id);
                      }
                    });
                  },
                },
              },
              "删除"
            );

            return h("div", [remove]);
          },
        },
      ],
      hospitaldata: [],
      removeId: [],
      lookDisabled: false,
      saveDisabled: false,
      delDisabled: false,
      disabledContrast: false,
      pageHospital: {
        pageNo: 1,
        pageSize: 10,
        count: 0,
      },
    };
  },
  computed: {},
  created() {
    let breadList = [
      { path: "/index", title: "首页" },
      {
        path: "",
        title: "药品目录管理",
      },
      {
        path: "/index/directory/institutional/list",
        title: "机构药品目录对照",
      },
    ];
    this.$emit("changeBreadList", breadList);
  },
  mounted() {
    if (this.mode !== "add") {
      this.findDrugsuccess();
      this.findDrugRecord();
    }
  },
  methods: {
    del(val) {
			if(val.del) {
				val.del = false
			} else {
				val.del = true
			}
			this.pendingList[val._index].del = val.del;
		},
    //同步院内目录
    directory() {
      this.disabled = true;
      this.$axios
        .post(api.findThirdhospitalDrug, { hospitalId: this.finalRecord.id })
        .then((res) => {
          if (res.data.code === 1) {
            this.$Message.success(res.data.message);
            this.directoryPage();
            setTimeout(() => {
              this.disabled = false;
            }, 10000);
          } else {
            this.$Message.error(res.data.message);
          }
        })
        .catch(() => {
          this.$Message.error(res.data.message);
        });
    },
    //点击查看院内数据
    lookdirectoryPage(pageNo) {
      this.lookDisabled = true;
      this.pageHospital.pageNo = pageNo;
      filterObj.pageNo = pageNo;
      this.directoryPage();
    },
    //同步数据列表
    directoryPage() {
      let params = {
        // params: {
          hospitalId: this.finalRecord.id,
        // },
        pageNo: this.pageHospital.pageNo,
        pageSize: this.pageHospital.pageSize,
        // pageSize: 100000,
      };
      this.$axios
        .post(api.findThirdDrugPage, params)
        .then((res) => {
          let ret = res.data.object;
          this.pageHospital.count = res.data.object.total;
          if (ret.records) {
            this.hospitaldata = ret.records;
            setTimeout(() => {
              this.lookDisabled = false;
            }, 6000);
          } else {
            this.hospitaldata = [];
            setTimeout(() => {
              this.lookDisabled = false;
            }, 6000);
          }
        })
        .catch(() => {
          this.$Message.error(res.data.message);
          setTimeout(() => {
            this.lookDisabled = false;
          }, 6000);
        });
    },
    //院内记录对照比对
    contrast(val) {
      this.disabledContrast = true;
      this.$axios
        .post(api.thirdContrast, { id: val })
        .then((res) => {
          if (res.data.code === 1) {
            let ret = res.data.object;
            this.$Message.success(res.data.message);
            this.directoryPage();
            setTimeout(() => {
              this.disabledContrast = false;
            }, 10000);
          } else {
            this.$Message.error(res.data.message);
            this.disabledContrast = false;
          }
        })
        .catch(() => {
          this.$Message.error(res.data.message);
          this.disabledContrast = false;
        });
    },
    //院内记录保存对照结果
    handledrugSave() {
      this.saveDisabled = true;
      const ids = [];
      if (this.hospitaldata && this.hospitaldata.length > 0) {
        this.hospitaldata.forEach((item) => {
          if (!item.del) {
            delete item.del;
            ids.push(item.id);
          }
          //如果对照结果有异常数据，终止forEach循环
          try {
            if (item.compareResult != "匹配成功") {
              setTimeout(() => {
                this.saveDisabled = false;
              }, 6000);
              throw new Error("End");
            } else {
              this.saveBtnLoading = true;
              this.$axios
                .post(api.saveDrugContrast, {ids})
                .then((res) => {
                  this.saveBtnLoading = false;
                  if (res.data.code === 1) {
                    this.handleCancel();
                    setTimeout(() => {
                      this.saveDisabled = false;
                    }, 6000);
                  } else {
                    this.$Message.error(res.data.message);
                  }
                })
                .catch(() => {
                  this.saveBtnLoading = false;
                });
            }
          } catch (e) {
            if (e.message === "End")
              throw this.$Message.error("没有对照成功的数据，不能入库");
          }
        });
      }
    },
    //删除院内记录
    handledrugDel() {
      this.delDisabled = true;
      if(this.removeId.length) {
        this.$axios
        .post(api.delDrugByids, { ids: this.removeId })
        .then((res) => {
          this.saveBtnLoading = false;
          if (res.data.code === 1) {
            this.directoryPage();
          } else {
            this.$Message.error("请勾选要删除的数据");
          }
          setTimeout(() => {
            this.delDisabled = false;
          }, 6000);
        })
        .catch(() => {
          this.saveBtnLoading = false;
          setTimeout(() => {
            this.delDisabled = false;
          }, 6000);
        });
      } else {
        this.$Message.error("请勾选要删除的数据");
        this.delDisabled = false
      }
    },
    onRowClick2(n, o) {
      this.currentChoose2 = n;
    },
    genRadioByType(h, params) {
		let curItem = this.failList.filter(
			(item) => params.row.id === item.id
		)[0];
		const type = params.row.type;
		let resDom = null;
		const isDisabled = this.mode === "review" || curItem.manualHandling;
		resDom = h("div", [
			h(
			"RadioGroup",
			{
				props: { value: curItem.manualHandling },
				on: {
				"on-change": (e) => {
					this.curRecord = curItem;
					this.$set(curItem, "manualHandling", curItem.manualHandling);
					// 单元框bug问题修复；
					if (!this.curRecord.manualHandling) {
					curItem.manualHandling = "";
					this.$nextTick(() => {
						curItem.manualHandling = null;
					});
					}
					if (e === "shanchu") {
					this.$Modal.confirm({
						title: "人工处理选择结果",
						content:
						"<p>人工处理结果<删除>确认该处理结果吗？处理后不可修改！</p>",
						loading: true,
						onOk: () => {
						this.delDrugContrastByRecordId();
						},
						onCancel: () => {},
					});
					} else if (e === "1") {
					this.$Modal.confirm({
						title: "人工处理选择结果",
						content:
						"<p>人工处理结果<匹配失败>确认该处理结果吗？处理后不可修改！</p>",
						loading: true,
						onOk: () => {
						this.updateRecordByHandling();
						},
						onCancel: () => {},
					});
					} else if (e === "2") {
					this.$Modal.confirm({
						title: "人工处理选择结果",
						content:
						"<p>人工处理结果<匹配失败，申请加入标准库>确认该处理结果吗？处理后不可修改！</p>",
						loading: true,
						onOk: () => {
						this.applyDrugContrast();
						},
						onCancel: () => {},
					});
					} else if (e === "3") {
					this.showChooseDrugModal2 = true;
					this.findOperateDrugPage();
					} else if (e === "4") {
					this.showChooseDrugModal2 = true;
					this.findRepeatList();
					}
				},
				},
			},
			[
				type !== "00" &&
				type !== "20" &&
				h(
					"Radio",
					{ props: { label: "1", disabled: isDisabled } },
					"匹配失败"
				),
				type === "01" &&
				h(
					"Radio",
					{ props: { label: "2", disabled: isDisabled } },
					"匹配失败，申请加入标准库"
				),
				type === "02" &&
				h(
					"Radio",
					{ props: { label: "3", disabled: isDisabled } },
					"忽略差异"
				),
				type === "22" &&
				h(
					"Radio",
					{ props: { label: "4", disabled: isDisabled } },
					"替换原匹配结果"
				),
				h(
				"Radio",
				{ props: { label: "shanchu", disabled: isDisabled } },
				"删除"
				),
			]
			),
		]);
		return resDom;
    },
    handleSave() {
      this.insertDrugContrast();
    },
    handleCancel() {
      this.functionJS.queryNavgationTo(
        this,
        "/index/directory/institutional/list",
        {}
      );
    },
    handleModalSave(record) {
      this.finalRecord = record;
      this.finalRecord.hospitalName = record.orgName;
      console.log(this.finalRecord);
      this.showChooseDrugModal = false;
      this.findDrugsuccess();
    },
    handleModalSave2() {
      if (this.curRecord.type === "02") {
        this.$Modal.confirm({
          title: "人工处理选择结果",
          content:
            "<p>人工处理结果<忽略差异>确认该处理结果吗？处理后不可修改！</p>",
          loading: true,
          onOk: () => {
            this.insertByignoreDifferences();
          },
          onCancel: () => {
           
          },
        });
      } else if (this.curRecord.type === "22") {
        this.$Modal.confirm({
          title: "人工处理选择结果",
          content:
            "<p>人工处理结果<替换原匹配结果>确认该处理结果吗？处理后不可修改！</p>",
          loading: true,
          onOk: () => {
            this.updateDrugContrastByRecordId();
          },
          onCancel: () => {
           
          },
        });
      }
    },
    handleShowUploadModal() {
      if (!this.finalRecord) {
        this.$Message.info("请先选择医疗机构");
        return;
      }
      this.showUploadModal = true;
    },
    chooseDep() {
      this.showChooseDrugModal = true;
    },
    modalPageChange2(index) {
      this.modalFilterObj2.pageNo = index;
      this.findOperateDrugPage();
    },
	//新导入可入库列表
    handleSuccess(res, file) {
      this.uploading = false;
      res = this.uploadFileDecrypt(res);
      if (res.object) {
        this.pendingList = res.object.successList;
        if(this.pendingList.length>0){
					this.pendingList.forEach(i =>{
						i.del = false
					})
				}
        this.findDrugRecord();
        if (res.code === 1) {
          this.$Message.success("上传成功");
        } else {
          this.$Message.error({ content: res.message, duration: 3 });
        }
      }
      this.showUploadModal = false;
    },
	//保存机构药品目录比对结果
    insertDrugContrast() {
      const reqSuccessList = [];
      if (this.pendingList && this.pendingList.length > 0) {
        this.pendingList.forEach((item) => {
          if (!item.del) {
            delete item.del;
            reqSuccessList.push(item);
          }
        });
      }
      this.saveBtnLoading = true;
      if(!reqSuccessList.length){
				this.pendingList = []
				this.saveBtnLoading = false;
				return this.$Message.success("保存成功");
			}else{
        this.$axios
          .post(api.insertDrugresult, reqSuccessList)
          .then((res) => {
            this.saveBtnLoading = false;
            if (res.data.code === 1) {
              this.handleCancel();
            } else {
              this.$Message.error(res.data.message);
            }
          })
          .catch(() => {
            this.saveBtnLoading = false;
          });
        }
    },
    successPageChange(pageNo) {
      this.pageSuccess.pageNo = pageNo;
      filterObj.pageNo = pageNo;
      this.findDrugsuccess();
    },
	//查看药品目录成功对照结果列表
    findDrugsuccess() {
      const reqObj = {
        hospitalId: this.$route.query.hospitalId || this.finalRecord.id,
        pageNo: this.pageSuccess.pageNo,
        pageSize: this.pageSuccess.pageSize,
        hospitalType: 1
      };
      this.successTableLoading = true;
      this.$axios
        .post(api.findDrugsuccessPage, reqObj)
        .then((res) => {
          this.successTableLoading = false;
          if (res.data.code === 1) {
            const ret = res.data.object.records;
            console.log(ret);
            this.successList = ret || [];
            this.pageSuccess.count = res.data.object.total;
            if (!ret || !ret.length) {
              // this.$Message.info('未查询到符合条件的记录')
            }
          } else {
            this.$Message.error("请求异常");
            return false;
          }
        })
        .catch(() => {
          this.successTableLoading = false;
        });
    },
    failurePageChange(pageNo) {
      this.pageFailure.pageNo = pageNo;
      filterObj.pageNo = pageNo;
      this.findDrugRecord();
    },
	//查看药品目录对照异常数据列表
    findDrugRecord() {
      const reqObj = {
        hospitalId: this.finalRecord.id,
        pageNo: this.pageFailure.pageNo,
        pageSize: this.pageFailure.pageSize,
      };
      this.failureTableLoading = true;
      this.$axios
        .post(api.findDrugRecordPage, reqObj)
        .then((res) => {
          this.failureTableLoading = false;
          if (res.data.code === 1) {
            const ret = res.data.object.records;
            this.failList = ret || [];
            this.pageFailure.count = res.data.object.total;
            if (!ret || !ret.length) {
              this.failList = [];
            }
          } else {
            this.$Message.error("请求异常");
            return false;
          }
        })
        .catch(() => {
          this.failureTableLoading = false;
        });
    },
	//删除单条比对结果
    delDrugContrastByRecordId() {
      this.$axios
        .post(api.delByRecordId, { id: this.curRecord.id })
        .then((res) => {
          if (res.data.code === 1) {
            this.$Message.success("操作成功");
            this.$Modal.remove();
          } else {
          }
          this.findDrugRecord();
        })
        .catch(() => {});
    },
	//更新比对记录状态
    updateRecordByHandling() {
      const reqObj = {
        id: this.curRecord.id,
        manualHandling: 1,
      };
      this.$axios
        .post(api.updateDrugRecord, reqObj)
        .then((res) => {
          if (res.data.code === 1) {
            this.$Message.success("操作成功");
            this.$Modal.remove();
          } else {
          }
          this.findDrugRecord();
        })
        .catch(() => {});
    },
	//申请加入标准库
    applyDrugContrast() {
      const reqObj = {
        id: this.curRecord.id,
      };
      this.$axios
        .post(api.applyDruglibrary, reqObj)
        .then((res) => {
          if (res.data.code === 1) {
            this.$Message.success("操作成功");
            this.$Modal.remove();
          } else {
          }
          this.findDrugRecord();
        })
        .catch(() => {});
    },
	//忽略差异入库
    insertByignoreDifferences() {
      const reqObj = {
        id: this.curRecord.id,
        standardCode: this.currentChoose2.id,
        hospitalid: this.finalRecord.id,
      };
      this.$axios
        .post(api.insertDifferences, reqObj)
        .then((res) => {
          if (res.data.code === 1) {
            this.$Message.success("操作成功");
            this.showChooseDrugModal2 = false;
          } else {
            this.$Message.error(res.data.message);
          }
          this.$Modal.remove();
          this.findDrugRecord();
        })
        .catch(() => {});
    },
	//历史重复差异替换原导入数据
    updateDrugContrastByRecordId() {
      const reqObj = {
        recordId: this.curRecord.id,
        drugContrastId: this.currentChoose2.id,
      };
      this.$axios
        .post(api.updateByRecordId, reqObj)
        .then((res) => {
          if (res.data.code === 1) {
            this.$Message.success("操作成功");
            this.showChooseDrugModal2 = false;
          } else {
            this.$Message.error(res.data.message);
          }
          this.$Modal.remove();
          this.findDrugRecord();
        })
        .catch(() => {});
    },
	//获取平台药品云目录列表
    findOperateDrugPage() {
      const reqObj = {
        ypmc: this.curRecord.ypmc,
        drugContrastHosId: this.finalRecord.id,
        pageNo: this.modalFilterObj2.pageNo,
        pageSize: this.modalFilterObj2.pageSize,
      };
      this.modalTableLoading2 = true;
      this.$axios
        .post(api.findDhtboDrugPageList, reqObj)
        .then((res) => {
          if (res.data.code === 1) {
            this.modalData2 = res.data.object.records;
            this.modalData2.unshift(this.curRecord);
            if (this.modalData2) {
              this.modalData2.forEach((item, index) => {
                if (index === 0) {
                  item.dataOrigin = "当前记录";
                } else {
                  item.dataOrigin = "标准库信息";
                  item.canCheck = true;
                }
              });
            }
            this.modalCount2 = res.data.object.total;
          } else {
          }
          this.modalTableLoading2 = false;
        })
        .catch(() => {
          this.modalTableLoading2 = false;
        });
    },
	//历史重复差异
    findRepeatList() {
      const reqObj = {
        id: this.curRecord.id,
      };
      this.modalTableLoading2 = true;
      this.$axios
        .post(api.findRepeatList, reqObj)
        .then((res) => {
          if (res.data.code === 1) {
            const oldDrugContras = res.data.object.oldDrugContras;
            this.modalData2[0] = { ...oldDrugContras };
            this.modalData2[1] = res.data.object.contrastRecord;
            this.modalData2[2] = {
              ypmc: oldDrugContras.standardYpmc,
              ypjx: oldDrugContras.ypjx,
              ypgg: oldDrugContras.standardYpgg,
              scqymc: oldDrugContras.standardScqymc,
              hisCode: oldDrugContras.standardCode,
              pzwh: oldDrugContras.standardPzwhd,
            };
            if (this.modalData2) {
              this.modalData2.forEach((item, index) => {
                if (index !== 2) {
                  item.canCheck = true;
                }
                if (index === 0) {
                  item.dataOrigin = "原记录";
                }
                if (index === 1) {
                  item.dataOrigin = "当前记录";
                }
                if (index === 2) {
                  item.dataOrigin = "标准库信息";
                }
              });
            }

            this.modalData2 = JSON.parse(JSON.stringify(this.modalData2));
            this.modalCount2 = res.data.object.total;
          } else {
          }
          this.modalTableLoading2 = false;
        })
        .catch(() => {
          this.modalTableLoading2 = false;
        });
    },
    download() {
      location.href = this.fileBaseUrl + "excel/drugContrastTemplate.xls";
    },
    deepClone(obj) {
      return JSON.parse(JSON.stringify(obj));
    },
  },
  watch: {
    showChooseDrugModal2(nv) {
      if (nv) {
        this.currentChoose2 = {};
      } else {
        this.modalData2 = [];
        this.modalCount2 = null;
      }
    },
    "modalFilterObj2.pageSize"() {
      this.findOperateDrugPage();
    },
    currentTab(n) {
      if (n === "success" && this.mode !== "review" && this.finalRecord.id) {
        this.findDrugsuccess();
      }
      if (
        n == "hospitalPage" &&
        this.mode !== "review" &&
        this.finalRecord.id
      ) {
        console.log(34567);
        this.directoryPage();
      }
    },
    hospitalInfo(n, o) {
      this.finalRecord = n;
    },
    failList: {
      handler(n) {
        console.log(n);
      },
      deep: true,
    },
  },
};
</script>

<style scoped lang="less">
.departmentDrug-add-page {
  width: 100%;
  min-width: 1200px;
  padding: 10px;
  margin: 0 auto;
  background: #fff;
  header {
    width: 100%;
    // position: relative;
    .buttonbox {
      height: 35px;
	  line-height: 15px;
    }
    .filter-part {
      display: flex;
      flex-wrap: wrap;
      margin: 10px 10px 10px 0;
      .filter-item {
        display: flex;
        line-height: 32px;
        &:first-child {
          label {
            width: auto;
          }
        }
        label {
          white-space: nowrap;
          line-height: 32px;
          width: 120px;
          text-align: right;
        }
        .input {
          width: 220px;
        }
        .select {
          width: 70px;
        }
      }
    }
    .fun-part {
      margin-bottom: 10px;
      margin-left: 20px;
      display: inline;
      a {
        vertical-align: bottom;
		color: #5326e1;
      }
    }
  }
  .btn-group {
    margin: 30px 0 10px;
    text-align: center;
    .btn-save {
      margin-right: 20px;
      text-align: center;
    }
  }  
}
.uploading {
	color: #5326e1;
}
.page{
      text-align: center;
      margin: 20px 0;
    }
.drugmanagement-departmentdrug-add-choose {
  /deep/ .ivu-modal-wrap {
    .ivu-modal-footer {
      display: none;
    }
    .btn-group {
      text-align: center;
      .save {
        width: 100px;
        margin-right: 20px;
      }
      .close {
        margin-left: 20px;
        width: 100px;
      }
    }
    .ivu-table .demo-table-info-row td {
      background-color: #5362e1;
      color: #fff;
    }
  }
  .paging {
    display: flex;
    justify-content: space-between;
    padding-top: 10px;
  }
}
.drugmanagement-departmentdrug-add-uplpadModal {
  /deep/ .ivu-modal-wrap {
    .ivu-modal-footer {
      display: none;
    }
    .btn-group {
      text-align: center;
      .save {
        width: 100px;
        margin-right: 20px;
      }
      .close {
        margin-left: 20px;
        width: 100px;
      }
    }
  }
  .download {
    text-align: center;
    padding: 20px;
    cursor: pointer;
	color: #5362e1;
  }
}
.drugmanagement-departmentdrug-list-delModal {
  /deep/ .ivu-modal-wrap {
    .ivu-modal-footer {
      display: none;
    }
    .btn-group {
      padding-top: 10px;
      text-align: center;
      .left {
        margin-right: 20px;
      }
      .right {
        margin-left: 20px;
      }
    }
    .content {
      text-align: center;
      .tip {
        padding-bottom: 10px;
        .hospitalName {
          color: rgb(253, 120, 58);
        }
      }
    }
  }
}
</style>